if [ $(uname) != 'Linux' ]
then
  echo 'This script can ONLY run on Linux!' >&2
  exit 1
fi

show_usage(){
  echo 'Input <project_name> <branch_name> <version>' >&2
}

if [ $# -lt 3 ]
then
  echo 'Invalid argument list. ' >&2
  show_usage
  exit 1
fi

project_name=$1
branch_name=$2
version=$3
shift 3
svnpath="http://bizsvn.sogou-inc.com/svn/"
codepath="/tmp"
date_format="+%Y-%m-%dT%H-%M-%S%z"

if [ $branch_name == "trunk" ]
then
    svnpath_pro=$svnpath$project_name"/trunk"
    deploy_tmp_dir="$(date $date_format)_$project_name_$branch_name"
else
    svnpath_pro=$svnpath$project_name"/branches/"$branch_name
    deploy_tmp_dir="$(date $date_format)_$branch_name"
fi

cd $codepath
svn info $svnpath_pro
if [ "$?" -ne 0 ]
then
  svn cp -m "Created BY Koala"  $svnpath$project_name"/trunk" $svnpath_pro 
  if [ "$?" -ne 0 ]
  then
    echo "svn create branch ${svnpath_pro} occur error, make sure you have the authority to access the repository!" >&2
    exit 1
  fi
fi

svn co $svnpath_pro $deploy_tmp_dir
if [ "$?" -ne 0 ]
then
  echo "svn co ${svnpath_pro} occur error, make sure you have the authority to access the repository!" >&2
  exit 1
fi
cd $deploy_tmp_dir
sed -i 's/version":.*",/version": "'$version'",/g' package.json
svn ci package.json -m 'modify version to '${version}''

if [ "$?" -ne 0 ]
then
  echo "svn commit ${project_name} occur error, make sure you have the authority to access the repository!" >&2
  exit 1
fi

sleep 1
rm -rf "${codepath}/${deploy_tmp_dir}"
